package com.grpc;
/*

                  写字楼里写字间，写字间里程序员；
                  程序人'猿'写程序，又拿程序换酒钱。
                  酒醒只在网上坐，酒醉还来网下眠；
                  酒醉酒醒日复日，网上网下年复年。
                  但愿老死电脑间，不愿鞠躬老板前；
                  奔驰宝马贵者趣，公交自行程序员。
                  别人笑我忒疯癫，我笑自己命太贱；
                  不见满街漂亮妹，哪个归得程序'猿'？
━━━━━━神兽出没━━━━━━
 ┏┓   ┏┓
┏┛┻━━━┛┻┓
┃       ┃
┃   ━   ┃
┃ ┳┛ ┗┳ ┃
┃       ┃
┃   ┻   ┃
┃       ┃
┗━┓   ┏━┛
  ┃   ┃                    神兽保佑, 永无BUG!
  ┃   ┃       Code is far away from bug with the animal protecting
  ┃   ┗━━━┓
  ┃       ┣┓
  ┃       ┏┛
  ┗┓┓┏━┳┓┏┛
   ┃┫┫ ┃┫┫
   ┗┻┛ ┗┻┛
 */

import com.grpc.client.GrpcClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import pb.GreeterGrpc;
import pb.HelloRequest;
import pb.HelloResponse;

import javax.annotation.Resource;

/**
 * Created by 石头哥哥 on 1/12/16.
 * <p>
 * grpc
 * <p>
 * server
 * <p>
 * comments:
 */
@SpringBootApplication
public class GrpcClientTest {

    private final Logger logger = LoggerFactory.getLogger(GrpcClientTest.class);


    @Resource
    private GrpcClient grpcClient;

    /**
     * do some logic
     * Say hello to server.
     */
    public void greet(String name) {
        try {
            logger.info("Will try to call remote method");

            //build blocking stub (client)----
            GreeterGrpc.GreeterBlockingStub greeterStub =
                    GreeterGrpc.newBlockingStub(grpcClient.getChannel());//获取远程操作客户端句柄

            //builder send data
            HelloRequest request = HelloRequest.newBuilder().setName(name).build();

            for (int i = 0;; ++i) {
                //调用远程方法
                HelloResponse response = greeterStub.sayHello(request);
                logger.info("Greeting: " + response.getMessage());//
                Thread.sleep(1000);
            }
        } catch (RuntimeException e) {
            logger.debug("RPC failed", e);
        } catch (Exception e) {
            logger.debug("RPC failed", e);
            e.printStackTrace();
        }
    }


    /**
     * Main launches the server from the command line.
     */
    public static void main(String[] args) throws Exception {
        ConfigurableApplicationContext applicationContext= SpringApplication.run(GrpcClientTest.class, args);
        GrpcClientTest client= (GrpcClientTest) applicationContext.getBean("grpcClientTest");
        client.greet("O(∩_∩)O~哈哈哈哈!!");
    }
}
